var BASE_URL = 'http://dev.dondereciclo.org//greentomato/dr-app/';
//var BASE_URL = 'http://'+window.location.host+'/apps/';

function Category () {
    this.id = new Number()
    this.markers = new Array ();
    this.texto = new String ();
    this.categoria = new String ();
}

var appPolygonsManager;

var controls = {
    detailsContainer: document.createElement('div')
};

function Categories () {
    this.defs = {
	categoryListContainer: document.createElement('div'),
	detailsContainer: document.createElement('div')
    }
    this.isLoad = false;
    this.list = [];
    this.load = function () {
	var self = this;
	$.ajax({
	    url: BASE_URL+'php/controllers/categoria.controller.php',
	    success: function (data) {
		var cat = {}, i;
                for (var n=0, l=INIT.length; n<l; n++) {
                    i = INIT[n];
                    cat = new Category ();
		    cat.id = data['categorias'][i]['id'];
		    cat.texto = data['categorias'][i]['nombre'];
		    cat.categoria = data['categorias'][i]['identificador'];
		    self.list[data['categorias'][i]['id']] = cat;
                }
		self.isLoad = true;
		$(document).ready(function () {
		    appMap = new MapController();
		    appMap.init();
		})
	    }
	})
    }
}

var appCategories = new Categories();
appCategories.load();

//MAP CONTROLLER
function MapController () {
    this.map = null;
    this.defs = {
	center: new google.maps.LatLng(-34.603526, -58.381586),
	container:'mapa-content'
    }
    this.options = {
	zoom: 11,
	mapTypeId: google.maps.MapTypeId.ROADMAP,
	disableDefaultUI: true,
	zoomControl: true,
        scrollwheel: false,
	zoomControlOptions: {
	    style: google.maps.ZoomControlStyle.SMALL
	}
    }
    this.init = function () {
	this.map = new google.maps.Map(document.getElementById(this.defs.container), this.options);
	this.map.setCenter(this.defs.center);
	var appSliderBox = new SliderBox();
	appSliderBox.create();

	controls.detailsContainer.index = -530;
	this.map.controls[google.maps.ControlPosition.TOP_RIGHT].push(controls.detailsContainer);

	appPolygonsManager = new PolygonsManager(appSliderBox);
	appPolygonsManager.init();
    }
}
//FIN MAP CONTROLLER

//POLYGONS MANAGER
function PolygonsManager (appSliderBox) {
    this.defs = {
        categorias: [],
        idsCategorias: [],
        infocooperativaTpl: document.getElementById('infomarkerTpl').value,
	detailsContaier: false
    }
    this.options = {
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillOpacity: 0.35
    }
    this.zonas = [], //informacion dinamica que viene de base
    this.bind = function (polygon) {
        self = this;
        google.maps.event.addListener(polygon, 'click', function(e) {
            if (!$('#marker-details-content').hasClass('active')) {
		appSliderBox.moving(controls.detailsContainer, 'det');
	    }
            self.mostrarDetallesCooperativa(polygon.id)
        });
    }
    this.mostrarDetallesCooperativa = function (id) {
        var self = this;
        if (!self.defs.detailsContaier) {
	    self.defs.detailsContaier = document.getElementById('marker-details-content');
	}
        $.ajax({
            url:BASE_URL+'php/controllers/infoCooperativa.controller.php',
            data:{id:id},
            type:'post',
            beforeSend:function () {
		self.defs.detailsContaier.innerHTML = '\
                    <div class="medium-loader" style="width:100%; min-height:430px">\
                        <div class="circle-container rad-border">\
                            <div class="circle-loader rad-border"></div>\
                            <div class="circle-content rad-border"></div>\
                            <div class="center-circle-image rad-border"></div>\
                        </div>\
                    </div>\
                ';
	    },
            success:function (data) {
                var tpl = self.defs.infocooperativaTpl.replace('${classyCategories}', self.classyCategories(data.categoriasToIds));
		var replacer = new Replacer();
		var html = replacer.itemReplace(tpl, data);
		self.defs.detailsContaier.innerHTML = html;
		appSliderBox.scrollEvents('marker-details-content');
                //oculta lo que no tiene info
                if (data.descripcion.length < 13)$('#description-item').remove();
                if (!data.telefono)$('#phone-item').remove();
                if (!data.horario)$('#hour-item').remove();
                if (!data.email)$('#email-item').remove();
                if (!data.web)$('#web-item').remove();
                if (data.direccion.length < 3)$('#address-item').remove();
                if (!data.categoriasToIds)$('#recive-item').remove();
                if (!data.images)$('#fotos-item').remove();
                $("a[rel=example_group]").fancybox({
                    'transitionIn'		: 'none',
                    'transitionOut'		: 'none'
                });
            }
        })
    }
    this.create = function () {
        var zona = null;
        var self = this, color;
        $.getJSON(BASE_URL+'php/controllers/cooperativas.controller.php', function(zonas) {
            for (var i in zonas) {
                color = '#'+ ('000000' + (Math.random()*0xFFFFFF<<0).toString(16)).slice(-6)
                zona = new google.maps.Polygon({
                    paths: eval(zonas[i].polygon),
                    strokeColor: color,
                    strokeOpacity: self.options.strokeOpacity,
                    strokeWeight: self.options.strokeWeight,
                    fillColor: color,
                    fillOpacity: self.options.fillOpacity,
                    id: zonas[i].id,
                    info: zonas[i].info,
                    nombre: zonas[i].nombre,
                    nombreUrl: zonas[i].nombreUrl,
                    centro: eval(zonas[i].centro)
                });
                zona.setMap(appMap.map);
                self.bind(zona);
            }
        });
    }
    this.init = function () {
        this.create();
    }
    this.classyCategories = function (c) {
	c = c.split(',');
	var html = '';
	for (var i=0, l=c.length; i<l; i++) {
            if (INIT.indexOf(c[i]*1) != -1) {
                html += '<em class="recive-item '+appCategories.list[c[i]].categoria+'-item"><span class="bg-color"></span><span class="val">'+appCategories.list[c[i]].texto+'</span></em>';
            }
	}
	return html;
    }
}
//FIN POLYGONS MANAGER

//SLIDER BOX
function SliderBox () {
    this.defs = {
	btn: document.createElement('input'),
	btnDetails: document.createElement('input'),
	isOpen: true
    }
    this.create = function () {
	controls.detailsContainer.id = 'marker-details-content';
	controls.detailsContainer.className = 'overflow';
	controls.detailsContainer.innerHTML = '\
            <div class="scrollear">\n\
                <div class="content">\
                    <div id="datos-row" class="span">\
                        <h3 class="title">Seleccione una cooperativa para ver la informaci&oacute;n</h3>\
                    </div>\
                </div>\
            </div>';

	this.defs.btnDetails.id = 'btn-expand-markers-details';
	this.defs.btnDetails.type = 'button';
	controls.detailsContainer.appendChild(this.defs.btnDetails);
	this.bind();
    }
    this.bind = function () {
	var self = this;
	$('#btn-expand-markers-details').live('click', function(){
	    self.moving(controls.detailsContainer, 'det');
	});
	self.scrollEvents('category-list-container');
    }
    this.moving = function (el, what){
	var move, obj;
	el = $(el);
	if (what == 'det') {
	    move = (window.innerWidth < 767) ? ($('#marker-details-content').width()-$('#btn-expand-markers-details', '#marker-details-content').outerWidth(true)+48) : 520;
	    obj = {
		'marginRight': move
	    };
	} else {
	    move = (window.innerWidth < 767) ? ($('#category-list-container').width()-$('#btn-expand-markers-list', '#category-list-container').outerWidth(true)) : 141;
	    obj = {
		'marginLeft': move
	    };
	}
	if (!el.hasClass('active')) {
	    el.addClass('active');
	    move = '+=' + move + 'px';
	} else {
	    el.removeClass('active');
	    move = '-=' + move + 'px';
	}
	if (what == 'det') {
	    obj = {
		'marginRight': move
	    };
	} else {
	    obj = {
		'marginLeft': move
	    };
	}
	el.animate(obj, {
	    duration: 500,
	    step: function() {
		google.maps.event.trigger(appMap.map, 'resize');
	    }
	});
    }
    this.scrollEvents = function (container){
	var self = this
	if (!!$('#' + container + '.overflow').length) {
	    var myScroll;
	    function loaded() {
		myScroll = new iScroll(container);
		if (!!myScroll.vScrollbarWrapper) {
		    myScroll.vScrollbarWrapper.setAttribute('class', 'scrollbar');
		}
	    }
	    /*document.addEventListener('touchmove', function (e) {
		e.preventDefault();
	    }, false);*/
            if(getInternetExplorerVersion() != '-1' && getInternetExplorerVersion() <= '8') {
                document.attachEvent('touchmove,', function (e) {
                    e.preventDefault();
                }, false);
                document.attachEvent('DOMContentLoaded', loaded, false);
            } 

            else {
                document.addEventListener('touchmove', function (e) {
                    e.preventDefault();
                }, false);
                document.addEventListener('DOMContentLoaded', loaded, false);
            }
	    loaded();
	} else {
	    setTimeout(function () {
		self.scrollEvents(container)
	    }, 1000)
	}
    }
}
//FIN SLIDER BOX



var resizeWindow = function(){
    var w = $(window), ww, b = $('body');
    w.resize(function(){
	mqClass();
    });
    function mqClass(){
	ww = $(window).width();
	if (ww <= 480) {
	    b.addClass('mq1200 mq979 mq767 mq480');
	} else if (ww <= 767) {
	    b.removeClass('mq480').addClass('mq1200 mq979 mq767');
	} else if (ww <= 979) {
	    b.removeClass('mq767 mq480').addClass('mq1200 mq979');
	} else if (ww <= 1200) {
	    b.removeClass('mq979 mq767 mq480').addClass('mq1200');
	}
    }
    mqClass();
};

window.onload = resizeWindow;

function getInternetExplorerVersion() {
   var rv = -1;
   if (navigator.appName == 'Microsoft Internet Explorer') {
      var ua = navigator.userAgent;
      var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
      if (re.exec(ua) != null)
         rv = parseFloat( RegExp.$1 );
   }
   return rv;
}